package com.cizzy.favorite.interceptor;

import cn.hutool.core.util.StrUtil;
import com.cizzy.favorite.common.UserIdHolder;
import com.cizzy.favorite.config.CizzyFinal;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

public class TokenInterceptor implements HandlerInterceptor {
    private StringRedisTemplate stringRedisTemplate;

    public TokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("Authorization");
        String userId = stringRedisTemplate.opsForValue().get(CizzyFinal.CIZZY_USER_GETID + authorization);
        if (StrUtil.isBlank(userId)) {
            return false;
        } else {
            UserIdHolder.saveUserId(Long.valueOf(userId));
            return true;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清除线程数据
        UserIdHolder.removeUserId();
    }
}
